{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "import pickle\n",
    "import numpy as np\n",
    "import os\n",
    "import json\n",
    "import random\n",
    "    \n",
    "# load source words\n",
    "source_words_path = os.path.join(os.getcwd(), 'source_words.pkl')\n",
    "with open(source_words_path, 'rb') as f_source_words:\n",
    "    source_words = pickle.load(f_source_words)\n",
    "    \n",
    "# load target words\n",
    "target_words_path = os.path.join(os.getcwd(), 'target_words.pkl')\n",
    "with open(target_words_path, 'rb') as f_target_words:\n",
    "    target_words = pickle.load(f_target_words)\n",
    "    \n",
    "# load label words\n",
    "label_words_path = os.path.join(os.getcwd(), 'label_words.pkl')\n",
    "with open(label_words_path, 'rb') as f_label_words:\n",
    "    label_words = pickle.load(f_label_words)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "945\n",
      "133\n",
      "27\n",
      "1\n",
      "3\n",
      "2\n",
      "0\n"
     ]
    }
   ],
   "source": [
    "print(len(source_words))\n",
    "print(len(target_words))\n",
    "print(len(label_words))\n",
    "print(source_words['<pad>'])\n",
    "print(source_words['<eos>'])\n",
    "print(source_words['<sos>'])\n",
    "print(source_words['<unk>'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 构建slotgate计算方式，利用slot context与intent context\n",
    "class SlotGate(nn.Module):\n",
    "    def __init__(self, hidden_dim):\n",
    "        super(SlotGate, self).__init__()\n",
    "        self.fc_intent_context = nn.Linear(hidden_dim, hidden_dim)\n",
    "        self.fc_v = nn.Linear(hidden_dim, hidden_dim)\n",
    "        \n",
    "    def forward(self, slot_context, intent_context):\n",
    "        '''\n",
    "        注意这里slot_context是slot上下文context，[batch_size, hidden_dim]，或者是时间步的hidden\n",
    "        intent_context:[batch_size, hidden_dim]\n",
    "        '''\n",
    "        # intent_context_linear:[batch_size, hidden_dim]\n",
    "        intent_context_linear = self.fc_intent_context(intent_context)\n",
    "        \n",
    "        # sum_intent_slot_context:[batch_size, hidden_dim]\n",
    "        sum_intent_slot_context = slot_context + intent_context_linear\n",
    "        \n",
    "        # fc_linear:[batch_size, hidden_dim]\n",
    "        fc_linear = self.fc_v(torch.tanh(sum_intent_slot_context))\n",
    "        \n",
    "        # sum_gate_vec:[batch_size]\n",
    "        sum_gate_vec = torch.sum(fc_linear, dim=1)\n",
    "        \n",
    "        return sum_gate_vec\n",
    "    \n",
    "# 这里计算slot context与intent context。就是bigru每个时间步隐藏特征的加权向量，这里不同于原论文，这里使用点乘来计算注意力权重weight\n",
    "class AttnContext(nn.Module):\n",
    "    def __init__(self, hidden_dim):\n",
    "        super(AttnContext, self).__init__()\n",
    "\n",
    "    def forward(self, hidden, source_output_hidden):\n",
    "        # source_output_hidden:[batch_size, seq_len, hidden_size]\n",
    "        # hidden:[batch_size, hidden_size]\n",
    "        hidden = hidden.unsqueeze(1) # [batch_size, 1, hidden_size]\n",
    "        \n",
    "        attn_weight = torch.sum(hidden * source_output_hidden,dim=2) # [batch_size, seq_len]\n",
    "        \n",
    "        attn_weight = F.softmax(attn_weight, dim=1).unsqueeze(1) # [batch_size, 1, seq_len]\n",
    "        \n",
    "        # 类似于注意力向量\n",
    "        attn_vector = attn_weight.bmm(source_output_hidden) # [batch_size, 1, hidden_size]\n",
    "        \n",
    "        return attn_vector.squeeze(1) # [batch_size, hidden_size]\n",
    "\n",
    "\n",
    "#构建模型\n",
    "class BirnnAttentionGate(nn.Module):\n",
    "    def __init__(self, source_input_dim, source_emb_dim, hidden_dim, n_layers, dropout, pad_index, slot_output_size, intent_output_size, seq_len, predict_flag, slot_attention_flag):\n",
    "        super(BirnnAttentionGate, self).__init__()\n",
    "        self.pad_index = pad_index\n",
    "        self.hidden_dim = hidden_dim//2 # 双向lstm\n",
    "        self.n_layers = n_layers\n",
    "        self.slot_output_size = slot_output_size\n",
    "        # 是否预测模式\n",
    "        self.predict_flag = predict_flag\n",
    "        # 原论文中有两种模型结构，一个带slot_attention，一个不带slot_attention\n",
    "        self.slot_attention_flag = slot_attention_flag\n",
    "        \n",
    "        self.source_embedding = nn.Embedding(source_input_dim, source_emb_dim, padding_idx=pad_index)\n",
    "        # 双向gru，隐层维度是hidden_dim\n",
    "        self.source_gru = nn.GRU(source_emb_dim, self.hidden_dim, n_layers, dropout=dropout, bidirectional=True, batch_first=True) #使用双向\n",
    "        \n",
    "        # slot context\n",
    "        self.slot_context = AttnContext(hidden_dim)\n",
    "        \n",
    "        # intent context\n",
    "        self.intent_context = AttnContext(hidden_dim)\n",
    "        \n",
    "        # slotgate类\n",
    "        self.slotGate = SlotGate(hidden_dim)\n",
    "        \n",
    "        # 意图intent预测\n",
    "        self.intent_output = nn.Linear(hidden_dim, intent_output_size)\n",
    "        \n",
    "        # 槽slot预测\n",
    "        self.slot_output = nn.Linear(hidden_dim, slot_output_size)\n",
    "        \n",
    "        \n",
    "    def forward(self, source_input, source_len):\n",
    "        '''\n",
    "        source_input:[batch_size, seq_len]\n",
    "        source_len:[batch_size]\n",
    "        '''\n",
    "        if self.predict_flag:\n",
    "            assert len(source_input) == 1, '预测时一次输入一句话'\n",
    "            seq_len = source_len[0]\n",
    "            \n",
    "            # 将输入的source进行编码\n",
    "            # source_embedded:[batch_size, seq_len, source_emb_dim]\n",
    "            source_embedded = self.source_embedding(source_input)\n",
    "            packed = torch.nn.utils.rnn.pack_padded_sequence(source_embedded, source_len, batch_first=True, enforce_sorted=True) #这里enfore_sotred=True要求数据根据词数排序\n",
    "            source_output, hidden = self.source_gru(packed)\n",
    "            # source_output=[batch_size, seq_len, 2 * self.hidden_size]，这里的2*self.hidden_size = hidden_dim\n",
    "            # hidden=[n_layers * 2, batch_size, self.hidden_size]\n",
    "            source_output, _ = torch.nn.utils.rnn.pad_packed_sequence(source_output, batch_first=True, padding_value=self.pad_index, total_length=len(source_input[0])) #这个会返回output以及压缩后的legnths\n",
    "            \n",
    "            batch_size = source_input.shape[0]\n",
    "            seq_len = source_input.shape[1]\n",
    "            # 保存slot的预测概率\n",
    "            slot_outputs = torch.zeros(batch_size, seq_len, self.slot_output_size)       \n",
    "                \n",
    "            aligns = source_output.transpose(0,1) # 为了拿到每个时间步的输出特征，即每个时间步的隐藏向量\n",
    "            \n",
    "            output_tokens =[]\n",
    "                \n",
    "            # 槽识别\n",
    "            for t in range(seq_len):\n",
    "                '''\n",
    "                此时刻时间步的输出隐向量\n",
    "                '''\n",
    "                aligned = aligns[t]# [batch_size, hidden_size]\n",
    "                    \n",
    "                # 是否需要计算slot attention\n",
    "                if self.slot_attention_flag:\n",
    "                    \n",
    "                    # [batch_size, hidden_size]\n",
    "                    slot_context = self.slot_context(aligned, source_output)\n",
    "                    \n",
    "                    # [batch_size, hidden_size]，意图上下文向量，利用bigru最后一个时间步的隐状态\n",
    "                    intent_context = self.intent_context(source_output[:,-1,:], source_output)\n",
    "                    \n",
    "                    # gate机制，[batch_size]\n",
    "                    slot_gate = self.slotGate(slot_context, intent_context)\n",
    "                    \n",
    "                    # slot_gate:[batch_size, 1]\n",
    "                    slot_gate = slot_gate.unsqueeze(1)\n",
    "                    \n",
    "                    # slot_context_gate:[batch_size, hidden_dim]\n",
    "                    slot_context_gate = slot_gate * slot_context\n",
    "                    \n",
    "                # 否则，利用每个时间步的隐状态与intent context计算slot gate\n",
    "                else:\n",
    "                     # [batch_size, hidden_size]，意图上下文向量，利用bigru最后一个时间步的隐状态\n",
    "                    intent_context = self.intent_context(source_output[:,-1,:], source_output)\n",
    "                    \n",
    "                    # gate机制，[batch_size]\n",
    "                    slot_gate = self.slotGate(source_output[:,t,:], intent_context)\n",
    "                    \n",
    "                     # slot_gate:[batch_size, 1]\n",
    "                    slot_gate = slot_gate.unsqueeze(1)\n",
    "                    \n",
    "                    # slot_context_gate:[batch_size, hidden_dim]\n",
    "                    slot_context_gate = slot_gate * source_output[:,t,:]\n",
    "                \n",
    "                \n",
    "                \n",
    "                # 预测槽slot, [batch_size, slot_output_size]\n",
    "                slot_prediction = self.slot_output(slot_context_gate + source_output[:,t,:])\n",
    "                \n",
    "                # 获取预测的最大概率的token\n",
    "                input = slot_prediction.argmax(1)\n",
    "\n",
    "                output_token = input.squeeze().detach().item()\n",
    "               \n",
    "                output_tokens.append(output_token)\n",
    "                \n",
    "                \n",
    "            #意图识别\n",
    "            intent_outputs = self.intent_output(intent_context + source_output[:,-1,:])\n",
    "            intent_outputs = intent_outputs.squeeze()\n",
    "            intent_outputs = intent_outputs.argmax()\n",
    "            return output_tokens, intent_outputs\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['i', 'would', 'like', 'to', 'find', 'a', 'flight', 'from', 'charlotte', 'to', 'las', 'vegas', 'that', 'makes', 'a', 'stop', 'in', 'st.', 'louis', '<eos>']\n",
      "[13, 40, 29, 4, 87, 16, 11, 5, 100, 4, 90, 89, 34, 345, 16, 127, 18, 67, 144, 3]\n",
      "len source :20\n",
      "slot_prediciton:o o o o o o o o b-fromloc.city_name o b-toloc.city_name i-toloc.city_name o o o o o b-stoploc.city_name o <eos>\n",
      "intent_prediction:airline\n"
     ]
    }
   ],
   "source": [
    "source_emb_dim = 64\n",
    "hidden_dim = 128\n",
    "n_layers = 1\n",
    "dropout = 0.5\n",
    "seq_len = 50\n",
    "\n",
    "model_path = os.path.join(os.getcwd(), \"model.h5\")\n",
    "\n",
    "input_dim = len(source_words) # source 词典大小（即词数量）\n",
    "output_dim = len(target_words) # target 词典大小（即实体类型数量）\n",
    "label_dim = len(label_words) # label 词典大小（即意图类别数量）\n",
    "\n",
    "model = BirnnAttentionGate(input_dim, source_emb_dim, hidden_dim, n_layers, dropout, source_words['<pad>'], output_dim, label_dim, seq_len, True, False)\n",
    "   \n",
    "model.load_state_dict(torch.load(model_path))\n",
    "model.eval()\n",
    "\n",
    "sentence = \"i would like to find a flight from charlotte to las vegas that makes a stop in st. louis\"\n",
    "sentence2 = \"which airlines have first class flights today\"\n",
    "with torch.no_grad():\n",
    "    tokenized = sentence.split()  # tokenize the sentence\n",
    "    tokenized.append('<eos>')\n",
    "    indexed = [source_words[t] for t in tokenized]  # convert to integer sequence\n",
    "    #pad = [1]*(seq_len - len(indexed))\n",
    "    #indexed.extend(pad)\n",
    "    print(tokenized)\n",
    "    print(indexed)\n",
    "    print('len source :{}'.format(len(indexed)))\n",
    "    tensor = torch.LongTensor(indexed)  # convert to tensor\n",
    "    tensor = tensor.unsqueeze(0)  # reshape in form of batch,no. of words\n",
    "    slot_outputs, intent_outputs = model(tensor, [len(tensor[0])])  # prediction\n",
    "    intent = intent_outputs.detach().item()\n",
    "    slot_prediction = [target_words.itos[t] for t in slot_outputs]\n",
    "\n",
    "    print('slot_prediciton:{}'.format(' '.join(slot_prediction)))\n",
    "    print('intent_prediction:{}'.format(label_words.itos[intent]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
